package com.xin.net
{
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/**
 * socket实现
 * @author daichangxin
 */
public class SocketClient extends EventDispatcher
{
	private var _socket:Socket;
	private var _port:uint;
	private var _host:String;
	
	private var _bytesLength:uint;
	
	public function SocketClient(host:String, port:uint)
	{
		_port = port;
		_host = host;
		
		init();
	}
	
	private function init() : void
	{
		_socket = new Socket();
		//连接关闭
		_socket.addEventListener(Event.CLOSE, function(e:Event):void
		{
			dispatchEvent(e);
		});
		
		//连接成功
		_socket.addEventListener(Event.CONNECT, function(e:Event):void
		{
			dispatchEvent(e);
		});
		
		//连接错误
		_socket.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void
		{
			onError(e.text);
		});
		
		//安全沙箱错误
		_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function(e:SecurityErrorEvent):void
		{
			onError(e.text);
		});
		
		//连接收取数据
		_socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
	}
	
	private function onSocketData(e:ProgressEvent):void
	{
		while (_socket.bytesAvailable > 4)
		{
			if (_bytesLength == 0)
			{
				_bytesLength = _socket.readInt();
			}
			if (_socket.bytesAvailable < _bytesLength) break;
			
			var byteArray:ByteArray = new ByteArray();
			_socket.readBytes(byteArray, 0, _bytesLength);
			var data:Object = byteArray.readObject();
			dispatchEvent(new SocketClientEvent(SocketClientEvent.DATA, data));
		}
	}
	
	/**
	 * 连接错误
	 */
	private function onError(msg:String):void
	{
		trace("socket connect error, msg: " + msg);
		dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, msg));
	}
	
	/**
	 * 连接
	 */
	public function connect():void
	{
		_socket.connect(_host, _port);
	}
	
	/**
	 * 发送数据到服务端
	 */
	public function send(data:Object):void
	{
		if (!_socket.connected) return;
		
		var byte:ByteArray = new ByteArray();
		byte.writeObject(data);
		
		_socket.writeUnsignedInt(byte.length);
		_socket.writeBytes(byte, 0, byte.length);
		_socket.flush();
	}
}
}
